<?php

namespace app\factory;

use app\factory\wxPay\CearteOrder;
use app\factory\wxPay\QueryOrder;
use app\model\agency\AgencyOrderModel;
use app\model\order\OrderModel;
use app\model\order\PayLogModel;
use app\model\store\StoreDepositModel;
use app\model\user\UserMemberOrderModel;
use app\model\user\UserModel;
use app\model\user\UserRechargeOrderModel;
use think\facade\Config;

/**
 * 支付
 * Class Pay
 * @package app\factory
 */
class Pay
{
    /**
     * 待支付订单信息
     * @param $formData
     * @param $userInfo
     * @return mixed
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function payPriceShow($formData, $userInfo)
    {
        $order_id = isset($formData['order_id']) ? $formData['order_id'] : "";//普通订单id，代理商订单
        $vip_id = isset($formData['vip_id']) ? $formData['vip_id'] : "";//订单id
        $pay_price = isset($formData['pay_price']) ? $formData['pay_price'] : "";//充值余额
        $pay_type = isset($formData['pay_type']) ? $formData['pay_type'] : "";//支付类型
        $pay_info = [];
        switch ($pay_type) {
            case 'pay':
                //订单支付
                $order_model = new OrderModel();
                $pay_info = $order_model->getOrderPayInfo($order_id, $userInfo['user_id']);
                break;
            case 'recharge':
                if (!is_numeric($pay_price) || $pay_price <= 0) {
                    throw new \think\Exception("充值参数错误，应当为数字", 0);
                }
                //余额充值
                $user_recharge_order_model = new UserRechargeOrderModel();
                $pay_info = $user_recharge_order_model->getBalanceInfo(floatval($pay_price), $userInfo['user_id']);
                break;
            case 'member':
                $user_recharge_order_model = new UserMemberOrderModel();
                $pay_info = $user_recharge_order_model->getMemberPayInfo($vip_id, $userInfo['user_id']);
                break;
            case 'agency':
                break;
            case 'deposit':
                //商户缴纳保证金
                $store_deposit_model = new StoreDepositModel();
                $pay_info = $store_deposit_model->getDepositPayInfo($order_id, $userInfo['user_id']);
                break;
        }
        if (empty($pay_info)) {
            $rsps['code'] = 0;
            $rsps['msg'] = "类型错误";
            return $rsps;
        }
        $UserModel = new UserModel();
        $userInfos = $UserModel->where("id", $userInfo['user_id'])->field("id,pay_price")->find();//用户余额
        $rsps['data']['userbalance'] = round(floatval($userInfos['pay_price']), 2);

        $bean_capital = UserModel::getBean($userInfo['user_id']);
        $bean_earnings = UserModel::getBeanEarnings($userInfo['user_id']);
        //总的趣豆
        $bean = floatval($bean_capital) + floatval($bean_earnings);
        //冻结的趣豆
        $freeze_bean = UserModel::getBeanFreeze($userInfo['user_id']);
        //可提现的趣豆
        $deposit_bean = $bean - floatval($freeze_bean);
        $rsps['data']['userbean'] = round($deposit_bean, 2);
        $rsps['data']['pay_price'] = round($pay_info['total'], 2);
        $rsps['data']['pay_sn'] = $pay_info['pay_sn'];
        $rsps['data']['order_id'] = $pay_info['order_id'];
        $pay = PayLogModel::getLog($pay_info['pay_sn']);
        $rsps['data']['time'] = $pay['add_time'];
        $rsps['code'] = 1;
        return $rsps;
    }


    /**
     * 确认支付
     * @param userInfo
     * @return \think\response\Json
     */
    public function ConfirmPay($formData, $userInfo)
    {
        $pay_sn = $formData['pay_sn'];
        $pay_type = $formData['pay_type'];
        $pay_mode = $formData['pay_mode'];
        if (isset($formData['openid'])) {
            $openid = $formData['openid'];
        }
        $order_total = 0;
        if ($pay_mode == "weixin") {
            switch ($pay_type) {
                case 'pay':
                    //支付订单
                    $pay_map = [
                        'pay_sn' => $pay_sn
                    ];
                    $order_model = new OrderModel();
                    $order_data = $order_model->where($pay_map)->field('id,order_total,freight_price')->select();
                    if (empty($order_data)) {
                        throw new \think\Exception("订单信息有误", 0);
                    }
                    $order_model->where($pay_map)->update(['pay_mode' => $pay_mode]);
                    $order_ids = [];
                    foreach ($order_data as $value) {
                        $order_ids[] = $value['id'];
                    }
                    if (count($order_ids) > 1) {
                        sort($order_ids);
                        $order_ids = implode('_', $order_ids);
                    } else {
                        $order_ids = $order_ids[0] . "";
                    }
                    $pay_info = $order_model->getOrderPayInfo($order_ids, $userInfo['user_id']);
                    $order_total = $pay_info['total'];
                    break;
                case 'recharge':
                    //余额充值
                    $pay_map = [
                        'pay_sn' => $pay_sn
                    ];
                    $user_recharge_order_model = new UserRechargeOrderModel();
                    $order_data = $user_recharge_order_model->where($pay_map)->field('price')->find();
                    if (empty($order_data)) {
                        throw new \think\Exception("订单信息有误", 0);
                    }
                    $user_recharge_order_model->where($pay_map)->update(['pay_mode' => $pay_mode]);
                    $order_total = $order_data['price'];
                    break;
                case 'member':
                    //会员缴费
                    $pay_map = [
                        'pay_sn' => $pay_sn
                    ];
                    $user_member_order_model = new UserMemberOrderModel();
                    $order_data = $user_member_order_model->where($pay_map)->field('price')->find();
                    if (empty($order_data)) {
                        throw new \think\Exception("订单信息有误", 0);
                    }
                    $user_member_order_model->where($pay_map)->update(['pay_mode' => $pay_mode]);
                    $order_total = $order_data['price'];
                    break;
                case 'agency':
                    //代理商进货支付
                    $pay_map = [
                        'pay_sn' => $pay_sn
                    ];
                    $agency_order_model = new AgencyOrderModel();
                    $order_data = $agency_order_model->where($pay_map)->field('order_total')->find();
                    if (empty($order_data)) {
                        throw new \think\Exception("订单信息有误", 0);
                    }
                    $agency_order_model->where($pay_map)->update(['pay_mode' => $pay_mode]);
                    $order_total = $order_data['order_total'];
                    break;
                case 'deposit':
                    //商户缴纳保证金
                    $pay_map = [
                        'pay_sn' => $pay_sn
                    ];
                    $store_deposit_model = new StoreDepositModel();
                    $order_data = $store_deposit_model->where($pay_map)->field('price')->find();
                    if (empty($order_data)) {
                        throw new \think\Exception("保证金订单信息有误", 0);
                    }
                    $store_deposit_model->where($pay_map)->update(['pay_mode' => $pay_mode]);
                    $order_total = $order_data['price'];
                    break;
            }
            //支付类型-微信支付
            $UserModel = new UserModel();
            $userInfos = $UserModel->where("id", $userInfo['user_id'])->field("wx_open_id")->find();//openid
            $pay = [
                'pay_sn' => $pay_sn,
                'pay_total_fee' => round($order_total, 2)
            ];
            if (empty($userInfos['wx_open_id'])) {
                $userInfos['wx_open_id'] = $openid;
            }
            $wxPayInfo = $this->wxPay($pay, $userInfos['wx_open_id']);
            $rsps['data']['wxPayInfo'] = $wxPayInfo;
            $rsps['data']['wxPayData'] = [
                'pay_sn' => $pay['pay_sn'],
                'pay_price' => $pay['pay_total_fee']
            ];
            $rsps['code'] = 1;
        } else if ($pay_mode == "balance") {
            switch ($pay_type) {
                case 'pay':
                    //支付订单
                    $pay_map = [
                        'pay_sn' => $pay_sn
                    ];
                    $order_model = new OrderModel();
                    $order_data = $order_model->where($pay_map)->field('id,order_total,freight_price')->select();
                    if (empty($order_data)) {
                        throw new \think\Exception("订单信息有误", 0);
                    }
                    $order_model->where($pay_map)->update(['pay_mode' => $pay_mode]);
                    $order_ids = [];
                    foreach ($order_data as $value) {
                        $order_ids[] = $value['id'];
                    }
                    if (count($order_ids) > 1) {
                        sort($order_ids);
                        $order_ids = implode('_', $order_ids);
                    } else {
                        $order_ids = $order_ids[0] . "";
                    }
                    $pay_info = $order_model->getOrderPayInfo($order_ids, $userInfo['user_id']);
                    $order_total = $pay_info['total'];
                    break;
                case 'member':
                    //会员缴费
                    $pay_map = [
                        'pay_sn' => $pay_sn
                    ];
                    $user_member_order_model = new UserMemberOrderModel();
                    $order_data = $user_member_order_model->where($pay_map)->field('price')->find();
                    if (empty($order_data)) {
                        throw new \think\Exception("订单信息有误", 0);
                    }
                    $user_member_order_model->where($pay_map)->update(['pay_mode' => $pay_mode]);
                    $order_total = $order_data['price'];
                    break;
                case 'agency':
                    //代理商进货支付
                    $pay_map = [
                        'pay_sn' => $pay_sn
                    ];
                    $agency_order_model = new AgencyOrderModel();
                    $order_data = $agency_order_model->where($pay_map)->field('order_total')->find();
                    if (empty($order_data)) {
                        throw new \think\Exception("订单信息有误", 0);
                    }
                    $agency_order_model->where($pay_map)->update(['pay_mode' => $pay_mode]);
                    $order_total = $order_data['order_total'];
                    break;
                case 'deposit':
                    //商户缴纳保证金
                    $pay_map = [
                        'pay_sn' => $pay_sn
                    ];
                    $store_deposit_model = new StoreDepositModel();
                    $order_data = $store_deposit_model->where($pay_map)->field('price')->find();
                    if (empty($order_data)) {
                        throw new \think\Exception("保证金订单信息有误", 0);
                    }
                    $store_deposit_model->where($pay_map)->update(['pay_mode' => $pay_mode]);
                    $order_total = $order_data['price'];
                    break;
            }
//            $password = $formData['password'];
//            $UserModel = new UserModel();
//            $res = $UserModel->verPayPassword($userInfo['user_id'], $password);
            $res['code'] = 1;
            if ($res['code'] === 1) {
                $pay = [
                    'pay_sn' => $pay_sn,
                    'pay_mode' => $pay_mode,
                    'pay_total_fee' => round($order_total, 2)
                ];
                //支付类型-余额支付
                $rsps = $this->balancePay($pay, $userInfo);
                return $rsps;
            } else {
                $rsps['code'] = 0;
                $rsps['msg'] = "支付失败";
            }
        } else if ($pay_mode == "bean") {
            $pay_map = [
                'pay_sn' => $pay_sn
            ];
            $order_model = new OrderModel();
            $order_data = $order_model->where($pay_map)->field('id,order_total,freight_price')->select();
            if (empty($order_data)) {
                throw new \think\Exception("订单信息有误", 0);
            }
            $order_model->where($pay_map)->update(['pay_mode' => $pay_mode]);
            $order_ids = [];
            foreach ($order_data as $value) {
                $order_ids[] = $value['id'];
            }
            if (count($order_ids) > 1) {
                sort($order_ids);
                $order_ids = implode('_', $order_ids);
            } else {
                $order_ids = $order_ids[0] . "";
            }
            $pay_info = $order_model->getOrderPayInfo($order_ids, $userInfo['user_id']);
            $order_total = $pay_info['total'];
//            $password = $formData['password'];
//            $UserModel = new UserModel();
//            $res = $UserModel->verPayPassword($userInfo['user_id'], $password);
            $res['code'] = 1;
            if ($res['code'] === 1) {
                $pay = [
                    'pay_sn' => $pay_sn,
                    'pay_mode' => $pay_mode,
                    'pay_total_fee' => round($order_total, 2)
                ];
                //支付类型-余额支付
                $rsps = $this->beanPay($pay, $userInfo);
                return $rsps;
            } else {
                $rsps['code'] = 0;
                $rsps['msg'] = "支付失败";
            }
        }
        return $rsps;
    }

    //微信支付-类型为weixin
    private function wxPay($pay, $openid)
    {
        $CearteOrder = new CearteOrder();//微信统一支付
        $wxParam['pay_sn'] = $pay['pay_sn'];
        $wxParam['pay_total_fee'] = $pay['pay_total_fee'];
        $wxParam['openid'] = $openid;
        $wx_res = $CearteOrder->set_sign($wxParam);
        if ($wx_res['return_code'] != "SUCCESS") {
            throw new \think\Exception($wx_res['return_msg'], 0);//只有普通订单可以余额支付
        }
        if ($wx_res['result_code'] == "SUCCESS" && $wx_res['result_code'] == "SUCCESS") {
            //小程序二次签名
            $wx["appId"] = $wx_res['appid'];
            $wx["timeStamp"] = "" . time();//时间戳
            $wx["nonceStr"] = $wx_res['nonce_str'];
            $wx["package"] = "prepay_id=" . $wx_res['prepay_id'];
            $wx["signType"] = "MD5";
            $sign = "appId=" . $wx["appId"] .
                "&nonceStr=" . $wx["nonceStr"] .
                "&package=" . $wx["package"] .
                "&signType=MD5" .
                "&timeStamp=" . $wx["timeStamp"] .
                "&key=" . Config::get('system.wx_pay.key');//秘钥
            $wx['paySign'] = strtoupper(md5($sign));//转大写
            unset($wx["appId"]);
            return $wx;
        } else {
            throw new \think\Exception($wx_res['err_code_des'], 0);
        }

    }

    /**
     * 查询支付结果
     * @param $formData
     * string $formData [pay_sn] 我的支付编号
     * int $formData [price] 支付金额
     * @return array
     * @throws \think\Exception
     */
    public function payQuery($formData)
    {
        $QueryOrder = new QueryOrder();//微信支付结果查询
        $pay_sn = $formData['pay_sn'];
        $price = floatval($formData['price']) * 100;
        $wx_res = $QueryOrder->set_sign($pay_sn);
        if ($wx_res['return_code'] != "SUCCESS") {
            throw new \think\Exception($wx_res['return_msg'], 0);//只有普通订单可以余额支付
        }
        $rsps = [];
        if ($wx_res['result_code'] == "SUCCESS" && $wx_res['result_code'] == "SUCCESS") {
            if ($wx_res['trade_state'] == "SUCCESS") {
                $res = PayHandle::pay_handle($pay_sn, $price, "weixin");//支付处理
                if ($res['code']) {
                    $rsps['code'] = 1;
                    $rsps['msg'] = "成功";
                } else {
                    $rsps['code'] = 0;
                    $rsps['msg'] = $res['msg'];
                }
            } else {
                $rsps['code'] = 0;
                $rsps['msg'] = "支付失败";
            }
            return $rsps;
        } else {
            throw new \think\Exception($wx_res['err_code_des'], 0);
        }
    }

    //用户余额支付
    private function balancePay($pay, $userInfo)
    {
        if ($pay['pay_mode'] != "balance") {
            throw new \think\Exception("支付类型错误", 0);//只有普通订单可以余额支付
        }
        $UserModel = new UserModel();
        $userInfos = $UserModel
            ->where("id", $userInfo['user_id'])
            ->field("id,earnings_price,pay_price")
            ->find();//用户余额
        $userBalance = $userInfos['earnings_price'] + $userInfos['pay_price'];
        if ($userBalance < $pay['pay_total_fee']) {
            throw new \think\Exception("余额不足", 0);
        }
        $res = PayHandle::pay_handle($pay['pay_sn'], $pay['pay_total_fee'], 'balance');
        if (!($res['msg'] == "成功" && $res['code'] == true)) {
            $rsps['code'] = 0;
            $rsps['msg'] = $res['msg'];
            return $rsps;
        }
        $rsps['code'] = 1;
        $rsps['msg'] = "成功";
        return $rsps;
    }

    //用户趣豆兑换
    private function beanPay($pay, $userInfo)
    {
        if ($pay['pay_mode'] != "bean") {
            throw new \think\Exception("支付类型错误", 0);//只有趣豆商城订单可以使用趣豆兑换
        }
        $UserModel = new UserModel();
        $userInfos = $UserModel
            ->where("id", $userInfo['user_id'])
            ->field("id,bean")
            ->find();//用户余额
        $userBean = $userInfos['bean'];
        if ($userBean < $pay['pay_total_fee']) {
            throw new \think\Exception("趣豆不足", 0);
        }
        $res = PayHandle::pay_handle($pay['pay_sn'], $pay['pay_total_fee'], 'bean');
        if (!($res['msg'] == "成功" && $res['code'] == true)) {
            $rsps['code'] = 0;
            $rsps['msg'] = $res['msg'];
            return $rsps;
        }
        $rsps['code'] = 1;
        $rsps['msg'] = "成功";
        return $rsps;
    }

}